﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Kooboo.Commerce.Domain;
using Kooboo.IoC;
using Kooboo.Domain;

namespace Kooboo.Commerce.Domain.Services
{
    public class BrandService:ServiceBase<IBrandRepository,IBrand>
    {
        //internal BrandService()
        //{
        //}

        public override IQueryable<IBrand> QueryService
        {
            get {
                return this.Repository.Brands;
            }
        }


        public void Post(IBrand brand)
        {
            var find = this.Repository.Brands
               .Any(i => i.Name == brand.Name);


            if (find)
            {
                throw new System.Data.DuplicateNameException(brand.Name);
            }

            using (var transaction = ObjectContainer.CreateInstance<TransactionContext>())
            {
                try
                {
                    this.Repository.Post(brand);
                    transaction.Commit();
                }
                catch
                {
                    transaction.Rollback();
                    throw;
                }
            }
        }

        public void Put(IBrand brand)
        {
            var find = this.Repository.Brands
                .Where(i => i.Name == brand.Name)
                .Select(i => i.Id)
                .FirstOrDefault();

            if (find != 0 && find != brand.Id)
            {
                throw new System.Data.DuplicateNameException(brand.Name);
            }

            using (var transaction = ObjectContainer.CreateInstance<TransactionContext>())
            {
                try
                {
                    this.Repository.Put(brand);
                    transaction.Commit();
                }
                catch
                {
                    transaction.Rollback();
                    throw;
                }
            }
        }

        public void Delete(IBrand brand)
        {
            
            using (var transaction = ObjectContainer.CreateInstance<TransactionContext>())
            {
                try
                {
                    brand.Products
                      .ToUpdate()
                      .Set(i => i.Brand, null)
                      .Execute();

                    
                    this.Repository.Delete(brand);

                    transaction.Commit();
                }
                catch
                {
                    transaction.Rollback();
                    throw;
                }
            }
        }
    }

  
}
